import jsonpath
from jsonpath_rw import Index, Fields
from jsonpath_rw_ext import parse

from common.logger import GetLogger


def update_value_to_json(json_object, json_path, new_value):
    json_path_expr = parse(json_path) # $.goods_name
    # print(json_path_expr)
    for match in json_path_expr.find(json_object):
        # print(match)
        path = match.path
        print(path)
        if isinstance(path, Index):
            match.context.value[match.path.index] = new_value
        elif isinstance(path, Fields):
            match.context.value[match.path.fields[0]] = new_value
    return json_object


def extract_json(json_object, json_path,index=0):
    resp = jsonpath.jsonpath(json_object, json_path)
    GetLogger.logger.info(f"从{json_object}中通过{json_path}提取到的结果是:{resp}")
    if resp:
        if index<0:
            return resp
        else:
            GetLogger.logger.info(f"提取的详情数据:{resp}")
            return resp[index]
    else:
        return resp

if __name__ == '__main__':
    json_data = {
        "goods_name":"商品名称",
        "price":300,
        "info":[
            {
                "aaa":"aaa",
                "bbb":"bbb"
            },
            {
                "aaa": "aaa1",
                "bbb": "bbb1"
            }
        ]
    }
    parmas = {
        "$.goods_name":"修改后的商品名称",
        "$.info[0].aaa":"new aaa1"

    }
    # new_json_data = update_value_to_json(json_data,"$.goods_name","修改后的商品名称")
    # print(new_json_data)
    # new_json_data = update_value_to_json(new_json_data, "$.info[0].aaa", "new aaa")
    # print(new_json_data)
    for json_path,new_value in parmas.items():
        json_data = update_value_to_json(json_data, json_path, new_value)
    print(json_data)